package com.liuym.admin.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.liuym.admin.properties.OssProperties;
import com.liuym.admin.repository.mapper.ExportLogMapper;
import com.liuym.admin.repository.model.entity.ExportLog;
import com.liuym.admin.service.ExportService;
import com.liuym.common.exception.AdminException;
import com.liuym.common.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;

/**
 * @author Liuym
 * @date 2019/4/19 17:11
 * @describe：
 */
@Service
public class ExportServiceImpl implements ExportService {

    private static Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class);


    @Autowired
    private ExportLogMapper exportLogMapper;
    @Autowired
    private OssProperties ossProperties;

    @Override
    public void export(String fileName, String filePath, List<String> titleList, List<List<String>> content, String userName, int type) throws AdminException {
        //开始导出数据为csv文件
        int per = 20;
        ExportLog exportLog = new ExportLog();
        exportLog.setUserName(userName);
        OSSClient ossClient = new OSSClient(ossProperties.endpoint,
                ossProperties.accessKeyId, ossProperties.accessKeySecret);
        //组装title
        StringBuffer titleString = new StringBuffer();
        titleList.stream().forEach(title -> {
            titleString.append(title + ",");
        });
        titleString.deleteCharAt(titleString.length() - 1);
        titleString.append("\n");
        String fileRealName = FileUtils.getObjectName(filePath, fileName, "csv");
        //拼接内容
        try {
            logger.info("开始上传文件:");
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("text/csv;charset=gbk");
            ByteArrayInputStream is = new ByteArrayInputStream(titleString.toString().getBytes("gbk"));
            AppendObjectRequest appendObjectRequest = new AppendObjectRequest(
                    ossProperties.bucketName, fileRealName, is, meta);
            appendObjectRequest.setPosition(0L);
            AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest);

            if (content != null && content.size() > 0) {
                StringBuffer csvContent = toCsv(content);
                appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
                appendObjectRequest.setInputStream(new ByteArrayInputStream(csvContent.toString().getBytes("gbk")));
                appendObjectResult = ossClient.appendObject(appendObjectRequest);

            }

        } catch (Exception e) {
            logger.error("上传异常！", e);
            throw AdminException.internalServerError();
        }
        ossClient.shutdown();
        exportLog.setPath(fileRealName);
        exportLog.setTitle(fileName);
        exportLog.setDate(new Date());
        exportLog.setType(type);
        exportLogMapper.insertSelective(exportLog);
        logger.info("上传完毕,fileName:{}", filePath);
    }

    private StringBuffer toCsv(List<List<String>> list) {
        StringBuffer content = new StringBuffer("");
        if (list != null && list.size() > 0) {
            list.stream().forEach(row -> {
                row.stream().forEach(column -> {
                    if (StringUtils.isBlank(column)) {
                        content.append("").append(",");
                    } else {
                        content.append(csvString(column)).append(",");
                    }

                });
                content.append("\n");
            });
        }
        return content;
    }

    private String csvString(String str) {
        if (!StringUtils.isBlank(str)) {
            if (str.contains(",")) {
                str = str.replace(",", "，");
            }
        }
        return str;
    }
}
